// Created by lifei on 2020/7/20--11:17.
import dataList from "@/components/dataList";
import projectTree from "../components/project-tree";
import dealRoom from "../components/deal-room";
import ocrAdd from "./ocr-add.vue";
import splitRoom from "../components/split-room";
import mergeRoom from "../components/merge-room";
import {
    initTreeData,
    getChild,
    search,
    queryPage,
    getStatistics,
    doDeal,
    doDelete,
    doSplit,
    validateMerge,
    doMerge
} from "../api/room.js";
import { getDict } from "~/utils";
import BaseLoad from "@/assets/vue-mixin/BaseLoad";
import { mapGetters } from "vuex";

export default {
    name: "resource-manage",
    mixins: [BaseLoad],
    components: {
        dataList,
        ocrAdd,
        projectTree,
        dealRoom,
        splitRoom,
        mergeRoom
    },
    computed: {
        ...mapGetters(["permissions"])
    },
    provide() {
        return {
            initList: this.getListData
        };
    },
    mounted() {
        this.useTypes = getDict("property_use_types");
        this.roomStatus = getDict("room_status");
        this.propertyTypes = getDict("property_types");
        this.propertyOwnerships = getDict("property_ownerships");
        this.propertySourceDict = getDict("property_source");
        //初始化树以及汇总统计
        //加载统计类型
        initTreeData().then(rep => {
            this.projectTree = rep.data.data.treeNode;
            this.statistics = rep.data.data.statisticsVos;
        });
        //获取列表数据
        this.getListData();
    },
    data() {
        return {
            useTypes: [],
            roomStatus: [],
            propertyTypes: [],
            propertyOwnerships: [],
            propertySourceDict: [],
            input: "",
            tableData: [],
            searchOptions: {},
            statistics: [],
            projectTree: [],
            nodeType: "",
            nodeId: "",
            selectionVals: [],
					   mergeDestroy: true,

            // 请求参数
            params: {
                current: 1,
                size: 20,
                propertyName: ""
            },
            // 分页
            pager: {
                total: 0, // 总页数
                current: 1, // 当前页数
                size: 20 // 每页显示多少条
            },
            // 页面loading
            loading: false,
            filterList: [
                {
                    label: "资产类型",
                    inputType: "dict",
                    dictName: "property_types",
                    name: "propertyType",
                    multiple: true
                },
                {
                    label: "资产用途",
                    inputType: "dict",
                    dictName: "property_use_types",
                    name: "useType",
                    multiple: true
                },
                {
                    label: "产权情况",
                    inputType: "dict",
                    dictName: "property_ownerships",
                    name: "propertyOwnership",
                    multiple: true
                },
                {
                    label: "资产状态",
                    inputType: "dict",
                    dictName: "room_status",
                    name: "propertyStatus",
                    multiple: true
                },
                {
                    label: "资产来源",
                    inputType: "dict",
                    dictName: "property_source",
                    name: "propertySource",
                    multiple: true
                },
                {
                    label: "是否VR",
                    inputType: "select",
                    name: "isVr",
                    multiple: true,
                    children: [
                        {
                            label: "是",
                            value: "1",
                            type: "input",
                            data: "1"
                        },
                        {
                            label: "否",
                            value: "0",
                            type: "input",
                            data: "0"
                        }
                    ]
                }
            ]
        };
    },
    methods: {
        orcShow() {
            this.$refs.roomOcr.show();
        },
        search(val) {
            search(this.input).then(rep => {
                this.projectTree = rep.data.data;
            });
        },
        getListData(params = {}) {
            this.loading = true;
            let requestData = { ...this.params, ...params };
            queryPage(Object.assign({ allQuery: "true" }, requestData))
                .then(res => {
                    const { current, size, total, records } = res.data.data;
                    this.tableData = records;
                    this.params = requestData;
                    this.pager = { total, current, size };
                })
                .finally(() => {
                    this.loading = false;
                });
        },
        toAdd() {
            this.$router.push({ name: "property_add" });
        },
        toEdit(row) {
            this.$router.push({
                name: "property_edit",
                query: { id: row.roomId, projectId: row.projectId }
            });
        },
        toLook(row) {
            this.$router.push({
                name: "property_look",
                query: { id: row.roomId, projectId: row.projectId }
            });
        },
				mergeRoomClose(){
        	this.mergeDestroy = false;
				},
        handleClick(item) {
            this.$router.push(
                "/property-info-sys/property-info-manage/resource-manage/edit"
            );
        },
        showChild(node, reqNodeType) {
            this.loadAction("数据加载中");
            node.showChildren = !node.showChildren;
            this.nodeType = reqNodeType;
            this.nodeId = node.nodeId;
            //如果没有子节点，则从数据库查询是否有子节点
            if (!node.children || node.children.length == 0) {
                //获取楼栋列表
                getChild(node.nodeId, reqNodeType)
                    .then(rep => {
                        this.loadClose();
                        node.children = rep.data.data.treeNode;
                    })
                    .catch(e => {
                        this.loadClose();
                    });
            } else {
                this.loadClose();
            }
        },
        initRightTable(node, type) {
            this.pager.currentPage = 1;
            //初始化右侧表单数据
            //统计数据
            if ("1" == type) {
                this.params.projectId = node.nodeId;
                this.params.buildingId = "";
                this.params.floor = "";
            }
            if ("2" == type) {
                this.params.projectId = "";
                this.params.buildingId = node.nodeId;
                this.params.floor = "";
            }
            if ("3" == type) {
                this.params.projectId = "";
                this.params.buildingId = "";
                this.params.floor = node.nodeId;
            }
            this.getListData();

            //统计数据
            getStatistics(node.nodeId, type).then(rep => {
                this.statistics = rep.data.data;
            });
            //列表数据
        },
        //格式化统计值
        formatterStatus(val) {
            let result = this.statistics.find(st => st.label == val);
            if (result) {
                return result.value;
            }
            return 0;
        },
        //字典翻译，此处根据列写死的 物业用途  物业类型 产权情况 物业状态 物业来源
        dictFormate: function(row, column, cellValue) {
            let columnTxt = column.property;
            //物业类型
            let dict;
            if ("propertyType" === columnTxt) {
                dict = this.propertyTypes.find(p => p.value == cellValue);
            }
            if ("useType" === columnTxt) {
                dict = this.useTypes.find(p => p.value == cellValue);
            }
            if ("propertyOwnership" === columnTxt) {
                dict = this.propertyOwnerships.find(p => p.value == cellValue);
            }
            if ("propertyStatus" === columnTxt) {
                dict = this.roomStatus.find(p => p.value == cellValue);
            }
            if ("propertySource" === columnTxt) {
                dict = this.propertySourceDict.find(p => p.value == cellValue);
            }
            if (dict) {
                return dict.label;
            }
            return "";
        },
        //资产处置方法
        dealRoom() {
            if (this.selectionVals.length == 0) {
                this.$alert("请选择要处置的物业信息！");
                return false;
            }
            // let facArr = this.selectionVals.find(sv => sv.facId != null);
            // if (facArr) {
            //     this.$alert(
            //         "选择的列表中包含了项目配套物业信息！配套物业信息不能进行处置操作"
            //     );
            //     return false;
            // }
            let arr = this.selectionVals.find(sv => sv.roomDealId != null);
            if (arr != null) {
                this.$alert("选择的列表中包含了已处置的物业信息！");
                return false;
            }
            this.$refs["dealRoom"].dialogVisible = true;
            this.$refs["dealRoom"].dealInfo = {
                dealType: "",
                dealArea: "",
                dealPrice: "",
                dealDate: "",
                remarks: ""
            };
            this.$refs["dealRoom"].dealRoomTab = this.selectionVals;
        },
        doDeal(data) {
            this.loadAction("保存中");
            doDeal(data)
                .then(rep => {
                    this.loadClose();
                    this.getListData();
                    this.$message.success("保存成功！");
                })
                .catch(e => {
                    this.loadClose();
                    this.$message.error("保存失败！");
                });
        },
        splitRoom() {
            if (this.selectionVals.length == 0) {
                this.$alert("请选择要拆分的物业信息！");
                return false;
            }
            if (this.selectionVals.length > 1) {
                this.$alert("请勿选择多条房源进行拆分操作！");
                return false;
            }
            //2020-12-28 空置状态物业才能进行拆分操作
					let noSplit = this.selectionVals.find(item => item.propertyStatus != "10")
					if(noSplit){
						this.$alert("非空置状态下的物业不能进行拆分操作！");
						return false;
					}


            //  2020-12-23 配套物业可以拆分
            // let facArr = this.selectionVals.find(sv => sv.facId != null);
            // if (facArr) {
            //     this.$alert(
            //         "选择的列表中包含了项目配套物业信息！配套物业信息不能进行拆分操作"
            //     );
            //     return false;
            // }
					//2020-12-24 增加如果建筑面积为空，则不允许进行拆分操作
					let noArea =  this.selectionVals.find(sv => sv.buildingArea == 0 || sv.buildingArea == "" || sv.buildingArea == null);
					if (noArea) {
						this.$alert(
						        "该物业没有建筑面积，不允许进行拆分操作！"
						    )
						return false
					}
            this.$refs["splitRoom"].dialogVisible = true;
            this.$refs["splitRoom"].sourceRoom = this.selectionVals[0];
            this.$refs["splitRoom"].fromData.roomInfo = [];
            this.$refs["splitRoom"].active = 0;
            let baseName = this.selectionVals[0].propertyName;
            if (
                this.selectionVals[0].splitMergeStatus == "1" ||
                this.selectionVals[0].splitMergeStatus == "2"
            ) {
                this.$refs["splitRoom"].baseRoomName = baseName.slice(
                    0,
                    baseName.lastIndexOf("-")
                );
            } else {
                this.$refs["splitRoom"].baseRoomName = baseName;
            }
        },
        //执行物业拆分
        doSplit(data) {
            this.loadAction("保存中");
            doSplit(data)
                .then(rep => {
                    this.loadClose();
                    this.getListData();
                    this.$message.success("拆分成功！");
                })
                .catch(e => {
                    this.loadClose();
                    this.$message.error("拆分失败！");
                });
        },
        doDelete() {
            if (this.selectionVals.length == 0) {
                this.$alert("请勾选要删除的数据！");
                return;
            }
            // let facArr = this.selectionVals.find(sv => sv.facId != null);
            // if (facArr) {
            //     this.$alert(
            //         "选择的列表中包含了项目配套物业信息！如需要删除请移至项目管理功能删除"
            //     );
            //     return false;
            // }
            //空置状态下的房源才可以删除
            let arr = this.selectionVals.find(sv => sv.propertyStatus != "10");
            if (arr) {
                this.$alert("选择的列表中包含了非空置状态的物业信息！");
                return false;
            }
            let ids = this.selectionVals.map(sd => sd.roomId);
            this.$confirm("此操作将永久删除该数据, 是否继续?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    doDelete(ids)
                        .then(rep => {
                            this.$message.success("删除成功");
                            this.getListData();
                        })
                        .catch(e => {
                            this.$message.error("删除失败");
                        });
                })
                .catch(() => {
                    this.$message.info("已取消删除");
                });
        },
        async mergeRoom() {
					if (this.selectionVals.length < 2) {
						this.$alert("请至少选择两个合并的物业信息！");
						return false;
					}

					let noMerge = this.selectionVals.find(item => item.propertyStatus != "10")
					if (noMerge) {
						this.$alert("非空置状态下的物业不能进行合并操作！");
						return false;
					}
					let spArr = this.selectionVals.find(
						sv =>
							sv.splitMergeStatus == "0" || sv.splitMergeStatus == "null"
					);
					if (spArr) {
						this.$alert("合并操作只能对已拆分的房源进行合并！");
						return false;
					}

					//  2020-12-23 配套物业可以合并
					// let facArr = this.selectionVals.find(sv => sv.facId != null);
					// if (facArr) {
					//     this.$alert(
					//         "选择的列表中包含了项目配套物业信息！配套物业信息不能进行合并操作"
					//     );
					//     return false;
					// }

					let baseName = this.selectionVals[0].propertyName;
					let bn = baseName.slice(0, baseName.lastIndexOf("-"));

					let noEq = this.selectionVals.find(
						sv => sv.propertyName.indexOf(bn) != 0
					);
					if (noEq) {
						this.$alert(
							"选择的房源不满足合并条件，合并要求：某房源拆分后生成多个房源，合并操作只能在这多个房源中进行！"
						);
						return false;
					}

					let ids = this.selectionVals.map(sv => {
						return sv.roomId;
					});
					let mergeFlag = false;
					await validateMerge({roomIds: ids}).then(rep => {
						mergeFlag = rep.data.data == 0;
					});

					if (!mergeFlag) {
						this.$alert(
							"选择的房源不满足合并条件，合并条件为【同一产权证下的同一栋楼、同一单元且同一楼层】！"
						);
						return false;
					}
					this.mergeDestroy = true
					this.$nextTick(() => {
							this.$refs["mergeRoom"].dialogVisible = true;
							this.$refs["mergeRoom"].active = 0;
							this.$refs["mergeRoom"].sourceRoom = this.selectionVals;
							this.$refs["mergeRoom"].baseRoomName = bn;
						}
					)
				}
        ,
        doMerge(data) {
					this.mergeDestroy = false;
            this.loadAction("保存中");
            doMerge(data)
                .then(rep => {
                    this.loadClose();
                    this.getListData();
                    this.$message.success("合并成功！");
                })
                .catch(e => {
                    this.loadClose();
                    this.$message.error("合并失败！");
                });
        },
        handleExportTable() {
            this.publicExport('物业管理','/api/roominfo/download',this.queryForm)
        },
        batchImport() {
            this.$router.push({ name: "property_batch_import" });
        },
        // 菜单点击监听
        handleMenuClick(type) {
            switch (type) {
                case "add":
                    this.toAdd();
                    break;
                case "test":
                    this.dealRoom();
                    break;
                case "test1":
                    this.orcShow();
                    break;
                case "test2":
                    this.splitRoom();
                    break;
                case "test3":
                    this.mergeRoom();
                    break;
                case "delete":
                    this.doDelete();
                    break;
                case "test4":
                    this.batchImport();
                    break;
                case "export":
                    this.handleExportTable();
                    break;
                default:
                    this.$message(type);
                    break;
            }
        }
    }
};
